<?php
class ControllerWxappPoint extends Controller {
  public function index(){
    $requestjson = file_get_contents('php://input');
    $data = json_decode($requestjson, true);
    $customer_id = $data['customer_id'];
    $userid=$data['userid'];
    if(empty($userid)){
      $this->load->model('wxapp/point');
    }
    $this->response->setOutput(json_encode($userid));
  }

  public function getProductById(){

    // $requestjson = file_get_contents('php://input');
    // $data = json_decode($requestjson, true);
    // var_dump($data);
    $sku = trim($this->request->get['sku']);

    // $shop_id = $data['shop_id'];
    if(isset($sku)){
          $this->load->model('wxapp/point');
            $this->load->model('tool/image');

      $data = $this->model_wxapp_point->getShopProductById($sku);

      foreach ($data as $key => $value) {
        $images = $this->model_wxapp_point->getImages($value['product_id']);
        foreach ($images as $key2 => $value2) {
          if ($value2['image'] != null && file_exists(DIR_IMAGE . $value2['image'])) {
                    $image = $this->model_tool_image->resize($value2['image'], $this->config->get('config_image_popup_width'), $this->config->get('config_image_popup_height'));
                }
                $imagesarr[] = $image;
        }
        if ($value['image'] != null && file_exists(DIR_IMAGE . $value['image'])) {
                  $image = $this->model_tool_image->resize($value['image'], $this->config->get('config_image_popup_width'), $this->config->get('config_image_popup_height'));
              } else {
                  $image = $this->model_tool_image->resize('no_image.jpg', $this->config->get('config_image_popup_width'), $this->config->get('config_image_popup_height'));
              }
              $description = $value['description'];
              $arr = explode( 'src',$description);
              foreach ($arr as $key1 => $value1) {
                $res =  $this ->_cut('http','jpg',$value1);
                if(strpos($res,'bhz360')===false){
                  continue;
                }
                $descriptionarr[] = 'http'.$res.'jpg';
              }
              $result = array(
                'image'=>$image,
                'images'=>$imagesarr,
                'product_id' => $value['product_id'],
                'product_code' => $value['product_code'],
                'price' => $value['sale_price'],
                'name' => $value['name'],
                'description' => $descriptionarr,
              );

       }
          if (empty($result)) {
            $json['error'] ='没有商品';

          }else{
            $json['result'] = $result;

          }
    }else{

      $json['error'] ='参数错误';
    }
    // var_dump($result);
    $this->response->setOutput(json_encode($json));

  }

  public function _cut($begin,$end,$str){
            $b = mb_strpos($str,$begin) + mb_strlen($begin);
            $e = mb_strpos($str,$end) - $b;

            return mb_substr($str,$b,$e);
  }

  //针对货架导出表格
  public function export(){
          $data['shop_id']= trim(I('get.shop_id'));
          $data['solution_id']= trim(I('get.solution_id'));
           $data['template']= trim(I('get.template'));
           $data['shelf_ids']= trim(I('get.shelf_ids'));
          $this->load->model('wxapp/point');
          //print_r($data);die;
          //导出excel表格
       if(!empty($data['solution_id'])){
         $results = $this->model_wxapp_point->getshelfinfo($data['solution_id']);
         //var_dump($results);die;
       }
       if(!empty($data['shop_id'])){
         $results = $this->model_wxapp_point->getshelf($data['shop_id']);
       }

       if(!empty($data['template'])){
          $results = $this->model_wxapp_point->getshelfinfo($data['template']);
       }

        if(!empty($data['shelf_ids'])){
          $results = $this->model_wxapp_point->getcheckshelf($data['shelf_ids']);
       }
        //var_dump($results);die;

          if($results){
               $this->load->library('PHPExcel/PHPExcel');
              $objPHPExcel = new PHPExcel();
              $objProps = $objPHPExcel->getProperties();
              $objProps->setCreator("Think-tec");
              $objProps->setLastModifiedBy("Think-tec");
              $objProps->setTitle("Think-tec Contact");
              $objProps->setSubject("Think-tec Contact Data");
              $objProps->setDescription("Think-tec Contact Data");
              $objProps->setKeywords("Think-tec Contact");
              $objProps->setCategory("Think-tec");
              $objPHPExcel->setActiveSheetIndex(0);
              $objActSheet = $objPHPExcel->getActiveSheet();

              $objActSheet->setTitle('Sheet1');
              $col_idx = 'A';
             $headers = array('方案','货架品类','货架长度', '货架名称', '商品名称',  'sku', '价格', '数量');
            $row_keys = array('shop_name','meta_title','shelf_length','shelf_name','name','sku','sale_price','show_qty');
            foreach ($headers as $header) {
                $objActSheet->setCellValue($col_idx++.'1', $header);
            }
              $i = 2;
              foreach ($results as $rlst) {
                $col_idx = 'A';
                foreach ($row_keys as $rk) {
                  $objActSheet->setCellValue($col_idx++.$i, $rlst[$rk]);
                }
                $i++;
              }

              $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');

              ob_end_clean();
              // Redirect output to a client’s web browser (Excel2007)
              header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
              header('Content-Disposition: attachment;filename="Shelfs_'.date('Y-m-d',time()).'.xlsx"');
              header('Cache-Control: max-age=0');
              // If you're serving to IE 9, then the following may be needed
              header('Cache-Control: max-age=1');

              // If you're serving to IE over SSL, then the following may be needed
              header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
              header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
              header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
              header ('Pragma: public'); // HTTP/1.0
              $objWriter->save('php://output');
              exit;
          }else{
            echo "数据有误....";
          }



  }

  public function addshelforder(){
        $now = date('Y-m-d H:i:s');
        $requestjson = file_get_contents('php://input');
        $data = json_decode($requestjson, true);
        $buyproducts = $data['buyproducts'];
        foreach ($buyproducts as $key => $value) {
            $productskey = $value['id']."_".$value['product_code'].'0';
            $shelfIds[] = $value['shelf_id'];
            $products[$productskey]['price'] = $value['special'];
            $products[$productskey]['buy_qty'] = $value['buyqty'];

            $products[$productskey]['shelf_info']['S']= $value['shelf_id'];
            $products[$productskey]['shelf_info']['Y']= $value['shelf_y'];
            $products[$productskey]['shelf_info']['X']= $value['shelf_x'];
            // .';Y:'.$value['shelf_y'].';X:'.$value['shelf_x'];
            $products[$productskey]['shelf_info']['qty'] = $value['buyqty'];
        }
        $shelfIds = array_unique($shelfIds);
        $shelfOrderId = $this->_shelfOrderSave($data, $shelfIds, $products, $now);
  }

   //数据添加shelf_order表+shelf_order_product表
    protected function _shelfOrderSave($data, $shelfIds, $products, $now) {
        $this->load->model('ssl/order');
        $this->load->model('ssl/shelf_order');
        //shelf_order添加
        $shelfOrderInfo = array(
            'customer_id' => $data['customerId'],
            'shelf_ids' => implode(',', $shelfIds),
            'add_name' => $data['sendaddress']['name'],
            'add_tel' => $data['sendaddress']['tel'],
            'add_country' => $data['sendaddress']['country'],
            'add_city' => $data['sendaddress']['city'],
            'add_zone' => $data['sendaddress']['zone'],
            'add_address' => $data['sendaddress']['address'],
            'add_company' => $this->model_ssl_order->getCompanyByAddressId($data['sendaddress']['address_id']),
            'paycode' => $data['paycode'],
            'order_price' => $data['allprice'],
            'date_added' => $now,
            'date_customer_check' => $now,
            'date_user_check' => $now,//调试创建订单方法
        );
        $shelfOrderId = $this->model_ssl_shelf_order->addNew($shelfOrderInfo);
        foreach ($products as $unique=>$info) {
            list($productId, $productCode) = explode('_', $unique);
            $shelfOrderProductInfo = array(
                'shelf_order_id' => $shelfOrderId,
                'customer_id' => $data['customerId'],
                'product_id' => $productId,
                'product_code' => $productCode,
                'shelf_info' => json_encode($info['shelf_info']),
                'price' => $info['price'],
                'buy_qty' => $info['buy_qty'],
            );
            $this->model_ssl_shelf_order->addNewProduct($shelfOrderProductInfo);
        }
        return $shelfOrderId;
    }


    //货架实景图上传
      public function imgUpload() {
        $customerId = intval($this->request->post['customerId']);
        $shelfid = intval($this->request->post['uploadId']);
        $type = intval($this->request->post['type']);
        $ret = array(
            'status' => false,
            'message' => '未知错误',
        );
        if ($customerId) {
            if (1 == $type) {
                $img = $this->request->files['picList'];
            }elseif (2 == $type){
                $img = $this->request->files['cardPic'];
            }elseif (3 == $type){
                $img = $this->request->files['LogoPic'];
            }elseif (4 == $type){
                $img = $this->request->files['Propaganda'];
            }elseif (5 == $type){
                $img = $this->request->files['shelfimage'];
            }
            $shop_id =M('customer')->where(array('customer_id'=>$customerId))->getField('shop_id');

            if ($img['error']) {
                $ret['message'] = '图片上传失败';
            }else{
                move_uploaded_file($img['tmp_name'], DIR_UPLOAD.$img['name']);

                if ($shelfid){
                    $uploadInfo = array(
                        'name' => $img['name'],
                        'filename' => $img['name'],
                    );
                    $data = "shelf_id=".$shelfid;
                    $shelf['shelf_image']=$img['name'];
                    $solution = M('shelf')->where($data)->save($shelf);
                }else{
                    $ret['message'] = '图片上传失败';
                }

                 $ret = $img['name'];
            }
        }
         $this->response->setOutput(json_encode($ret));
    }
    //刷shelf_class3
     public function classify(){
       $classifyinfo= $this->db->query("SELECT sh.shelf_id,p.product_class3  from  shelf_product as sh LEFT JOIN product as p  on  p.product_id=sh.product_id");
       foreach ($classifyinfo->rows as $key => $value) {
            $arr[$value['shelf_id']][$value['product_class3']]=$value['product_class3'];
       }
        foreach ($arr as $key => $value) {
            $arr[$key]=implode(',', $value);
        }

        foreach ($arr as $key => $value) {
          $info = $this->db->query("UPDATE shelf set shelf_class3='".$value."' where shelf_id=".$key);
          //var_dump($info);die;
        }
    }

    //获取商铺customer_id
    public function getshopcustomerid(){
        $input = file_get_contents('php://input');
        $data = json_decode($input, true);
        $shop_id = $data['shopid'];

        $customer_id = M('shop')->where(array('shop_id'=>$shop_id))->getField('customer_id');
        $this->response->setOutput(json_encode($customer_id));
    }
    //在线补货临时数量
    public function stock_qty(){
          $shelf_product_id= trim(I('get.shelf_product_id'));
          $add = trim(I('get.add'));
          $select = $this->db->query("select stock_qty from shelf_product where shelf_product_id=".$shelf_product_id)->row;
          $num = (int)$select['stock_qty']+(int)$add;
          //var_dump($num);die;
          $save = $this->db->query("UPDATE shelf_product SET stock_qty=".$num." WHERE shelf_product_id=".$shelf_product_id);

         if($save){
              $this->response->setOutput(json_encode($save));
         }
    }
    //在线补货减少数量
    public function reduce_qty(){
         $shelf_product_id = trim(I('get.shelf_product_id'));
          $reduced = trim(I('get.reduced'));
          $select = $this->db->query("select stock_qty from shelf_product where shelf_product_id=".$shelf_product_id)->row;
          $num = (int)$select['stock_qty']-(int)$reduced;
           //var_dump($num);die;
              $save = $this->db->query("UPDATE shelf_product SET stock_qty=".$num." WHERE shelf_product_id=".$shelf_product_id);

             if($save){
                  $this->response->setOutput(json_encode($save));
             }

    }
    //建议补货数量
    public function suggest(){
      $shelf_product_id= trim(I('get.shelf_product_id'));
          $add = trim(I('get.add'));
          $save = $this->db->query("UPDATE shelf_product SET stock_qty=".$add." WHERE shelf_product_id=".$shelf_product_id);
             if($save){
                  $this->response->setOutput(json_encode($save));
             }
    }

    //补货货架内查询
    // public function search(){
    //   $searchInput = trim(I('get.searchInput'));
    //   $shopid = trim(I('get.shopid'));
    //   "select sp.*,s.shelf_id from shelf_product AS sp LEFT JOIN shelf AS s ON s.shelf_id=sp.shelf_id where s.status=1 AND s.shop_id=".$shop_id."AND sp."
    // }
    //补货清单
    public function inventory(){
      $shop_id = trim(I('get.shop_id'));
      $this->load->model('wxapp/point');
      $data = $this->model_wxapp_point->cart($shop_id);
      foreach ($data as $key => $value) {
        $data[$key]['product']=$this->getProductInfo($value['product_id']);
      }

       $this->response->setOutput(json_encode($data));
    }
    //获取单个商品信息
     public function getProductInfo($data){

        $this->load->model('catalog/product');

        $retval = array();

        $result = $this->model_catalog_product->getListProduct($data);

        if($result){

            $product = $result[0];

            $this->load->model('tool/image');
            $this->load->model('catalog/category');

            /*product image*/
            if ($product['image'] != null && file_exists(DIR_IMAGE . $product['image'])) {
                $image = $this->model_tool_image->resize($product['image'], 100, 100);
            } else {
                $image = $this->model_tool_image->resize('no_image.jpg', 100, 100);
            }
            /*product image*/

            /*options选项*/
            foreach ($this->model_catalog_product->getProductOptions($product['product_id']) as $option) {
                if ($option['type'] == 'select' || $option['type'] == 'radio' || $option['type'] == 'checkbox' || $option['type'] == 'image') {
                    $option_value_data = array();
                    if(!empty($option['product_option_value'])){
                        foreach ($option['product_option_value'] as $option_value) {
                            //!$option_value['subtract'] || ($option_value['quantity'] > 0)
                            if (true) {
                                if ((($this->customer->isLogged() && $this->config->get('config_customer_price')) || !$this->config->get('config_customer_price')) && (float)$option_value['price']) {
                                    $price = $this->currency->restFormat($this->tax->calculate($option_value['price'], $product['tax_class_id'], $this->config->get('config_tax')));
                                    $price_formated = $this->currency->format($this->tax->calculate($option_value['price'], $product['tax_class_id'], $this->config->get('config_tax')));
                                } else {
                                    $price = $this->currency->restFormat($this->tax->calculate(0, $product['tax_class_id'], $this->config->get('config_tax')));
                                    $price_formated = $this->currency->format($this->tax->calculate(0, $product['tax_class_id'], $this->config->get('config_tax')));
                                }

                                if (isset($option_value['image']) && file_exists(DIR_IMAGE . $option_value['image'])) {
                                    $option_image = $this->model_tool_image->resize($option_value['image'], $this->config->get('config_rest_api_image_width'), $this->config->get('config_rest_api_image_height'));
                                } else {
                                    $option_image = $this->model_tool_image->resize('no_image.jpg', $this->config->get('config_rest_api_image_width'), $this->config->get('config_rest_api_image_height'));
                                }

                                $option_value_data[] = array(
                                    'image'                 => $option_image,
                                    'price'                 => $price,
                                    'price_formated'        => $price_formated,
                                    'price_prefix'          => $option_value['price_prefix'],
                                    'product_option_value_id'=> $option_value['product_option_value_id'],
                                    'option_value_id'       => $option_value['option_value_id'],
                                    'name'                  => $option_value['name'],
                                    'quantity'  => !empty($option_value['quantity']) ? $option_value['quantity'] : 0
                                );
                            }
                        }
                    }
                    $options[] = array(
                        'name'              => $option['name'],
                        'type'              => $option['type'],
                        'option_value'      => $option_value_data,
                        'required'          => $option['required'],
                        'product_option_id' => $option['product_option_id'],
                        'option_id'         => $option['option_id'],
                        'flag' => true

                    );

                } elseif ($option['type'] == 'text' || $option['type'] == 'textarea' || $option['type'] == 'file' || $option['type'] == 'date' || $option['type'] == 'datetime' || $option['type'] == 'time') {
                    $option_value  = array();
                    if(!empty($option['product_option_value'])){
                        $option_value = $option['product_option_value'];
                    }
                    $options[] = array(
                        'name'              => $option['name'],
                        'type'              => $option['type'],
                        'option_value'      => $option_value,
                        'required'          => $option['required'],
                        'product_option_id' => $option['product_option_id'],
                        'option_id'         => $option['option_id'],
                        'flag' => true
                    );
                }
            }
            /*options选项*/

            /*原价*/
            $price = $this->currency->restFormat($this->tax->calculate($product['price'], $product['tax_class_id'], $this->config->get('config_tax')));
            $price_formated = $this->currency->format($this->tax->calculate($product['price'], $product['tax_class_id'], $this->config->get('config_tax')));
            /*原价*/

            /*原价*/
            $sale_price = $this->currency->restFormat($this->tax->calculate($product['sale_price'], $product['tax_class_id'], $this->config->get('config_tax')));
            $sale_price_formated = $this->currency->format($this->tax->calculate($product['sale_price'], $product['tax_class_id'], $this->config->get('config_tax')));
            /*原价*/

            /*special特价*/
            if ((float)$product['special']) {
                $special = $this->currency->restFormat($this->tax->calculate($product['special'], $product['tax_class_id'], $this->config->get('config_tax')));
                $special_formated = $this->currency->format($this->tax->calculate($product['special'], $product['tax_class_id'], $this->config->get('config_tax')));
            }
            /*special特价*/

            $show_cart = 1;
            if($product['is_single'] != 1){
                $show_cart = 0;
            }
            else if( $options[0]['option_value'][0]['quantity'] < $product['minimum']){
                $show_cart = 2;
            }

            $days = (int)((time()-strtotime($product['date_added']))/(24*3600));
            if(($days < 60 || $product['newpro'] == 1) && $product['show_new'] == 1){
                $show_new = 1;
            }
            else{
                $show_new = 0;
            }
            // if ($product['clearance']||$product['lack_status']==3) {
                $clearqty = $this->model_catalog_product->getclearqty($product['product_id']);
            // }
            $parameter=substr($product['sku'], -6);
            $retval = array(
                'id' => $product['product_id'],
                'product_code' => $product['product_code'],
                'sku' => $product['sku'],
                'parameter' => $parameter,
                'name' => $product['name'],
                'image' => $image,
                'price' => $price,
                'price_formated'    => $price_formated,
                'special' => $special,
                'special_formated'  => $special_formated,
                'minimum' => $product['minimum'] ? $product['minimum'] : 1,
                'options'    => $options,
                'quantity' => $product['quantity'],
                'show_new' => $show_new,
                'recommend' => $product['recommend'],
                'clearance' => $product['clearance'],
                'lack_status' => $product['lack_status'],
                'lack_reason' => $product['lack_reason'],
                'promotion' => $product['promotion'],
                'is_single' => $product['is_single'],
                'option_value_quantity' => $options[0]['option_value'][0]['quantity'],
                'show_cart' => $show_cart,
                'clearqty' => $clearqty ,
                'sort_order' => $product['sort_order']
            );

            return $retval;

        }

    }
    //清除补货数量
    public function delstockqty(){
         $shelf_product_id = trim(I('get.shelf_product_id'));
          $save = $this->db->query("UPDATE shelf_product SET stock_qty=0 WHERE shelf_product_id=".$shelf_product_id);
         if($save){
              $this->response->setOutput(json_encode($save));
         }
    }

    //商家修改商品售价
    public function saveshopprice(){
        $requestjson = file_get_contents('php://input');
        $data = json_decode($requestjson, true);
        $shop_product_id = $data['shop_product_id'];
        $price = $data['price'];
        $end = $this->db->query("UPDATE shop_product set price=".$price." where shop_product_id=".$shop_product_id);
         $this->response->setOutput(json_encode($end));
    }
    //商家修改商品优惠价
   public function savesaleprice(){
        $requestjson = file_get_contents('php://input');
        $data = json_decode($requestjson, true);
        $shop_product_id = $data['shop_product_id'];
        $price = $data['price'];
        $end = $this->db->query("UPDATE shop_product set sale_price=".$price." where shop_product_id=".$shop_product_id);
         $this->response->setOutput(json_encode($end));
   }
   //修改单品上线状态
   public function saveskustatus(){
        $requestjson = file_get_contents('php://input');
        $data = json_decode($requestjson, true);
        $shop_product_id = $data['shop_product_id'];
        $status = $data['status'];
        $end = $this->db->query("UPDATE shop_product set status=".$status." where shop_product_id=".$shop_product_id);
         $this->response->setOutput(json_encode($end));
   }
   //上传店铺新品图片
    public function addNewProduct() {
        $type = intval($this->request->post['type']);

        $ret = array(
            'status' => false,
            'message' => '未知错误',
        );
            if (1 == $type) {
                $img = $this->request->files['picList'];
            }elseif (2 == $type){
                $img = $this->request->files['cardPic'];
            }elseif (3 == $type){
                $img = $this->request->files['LogoPic'];
            }elseif (4 == $type){
                $img = $this->request->files['Propaganda'];
            }elseif (5 == $type){
                $img = $this->request->files['shelfimage'];
            }elseif(6 == $type){
                $img = $this->request->files['newproductpic'];
            }

            if ($img['error']) {
                $ret['message'] = '图片上传失败';
            }else{
                move_uploaded_file($img['tmp_name'], DIR_UPLOAD.$img['name']);
                 $uploadInfo = array(
                        'name' => $img['name'],
                        'filename' => $img['name'],
                    );

                 $ret= $img['name'];
            }

               echo $ret;

    }
    //获取一级分类
    public function getCategoryClass(){
        $parent_id = intval($this->request->get['parent_id']);
         $class = M('shop_category')
          ->alias('c')
          ->join('shop_category_description cd on c.category_id = cd.category_id','left')
          ->field('cd.name,c.category_id')
          ->where('c.code != "" AND c.status = 1 AND c.parent_id = '.$parent_id)->select();
          if(empty($class)){
            $class =1;
          }
            $this->response->setOutput(json_encode($class));

  }
  //搜索补货商品
    public function searchrepair(){
      $searchInput = trim(I('get.searchInput'));
      $shopid = trim(I('get.shopid'));
      $this->load->model('wxapp/point');
      $data = $this->model_wxapp_point->searchrepair($shopid,$searchInput);

      foreach ($data as $key => $value) {
        $data[$key]['product']=$this->getProductInfo($value['product_id']);
      }
        if(empty($data)){
            $data = 0;
        }
       $this->response->setOutput(json_encode($data));

    }
    //上传新品
    public function savenewproduct(){
        $requestjson = file_get_contents('php://input');
        $data = json_decode($requestjson, true);
        $gather = $data['gather'];
        $gather = explode(',', $gather);
        $length=count($gather);
        if($length==3){
          $newproductinfo['product_class1'] = $gather[0];
          $newproductinfo['product_class2'] = $gather[1];
          $newproductinfo['product_class3'] = $gather[2];
        }else if($length==2){
          $newproductinfo['product_class1'] = $gather[0];
          $newproductinfo['product_class2'] = $gather[1];
          $newproductinfo['product_class3'] = 0;
        }else if($length==1){
          $newproductinfo['product_class1'] = $gather[0];
          $newproductinfo['product_class2'] = 0;
          $newproductinfo['product_class3'] = 0;
        }

        $shop_id = $data['shopid'];
        $length = $this->db->query("SELECT count(*) as `long` from `shop_product` where shop_id=".$shop_id)->row;
        $length = intval($length['long'])+1;
        $shop_basic_code = $shop_id.'_'.$length;
        $newproductinfo['shop_basic_code'] = $shop_basic_code;//商品编码
        $newproductinfo['sku'] = $data['code'];//sku
        $newproductinfo['price'] = $data['newprice'];//新品价格
        $newproductinfo['sale_price'] = $data['sale_price'];//优惠价
        $newproductinfo['date_added'] = date("y-m-d h:i:s",time());//添加时间
        $newproductinfo['shop_id'] = $shop_id;//商铺id
        if($data['shelf_id']){
            $newproductpic['shelf_id'] = $data['shelf_id'];//货架id
        }else{
            $newproductpic['shelf_id'] = 0;//货架id
        }
        $newproductpic['name'] = $data['newname'];//新品名称
        $newproductpic['image'] = $data['iamgepath'];//主图
        $shopproductId = M('shop_product')->add($newproductpic);
        // if($data['shelf_id']){
        //     $this->db->query("INSERT INTO `" . DB_PREFIX . "shelf_product` SET shelf_id = ".$data['shelf_id']." , product_id = 0, product_code = 0, shelf_layer = 0, layer_position = 0, attr_list = 0, group_name =0, show_qty = 1, min_order_qty = 1, date_added = NOW(), `stock_qty`=0, `stock_qty_temp`=0, `shop_inventory_id`=0 ,`shop_product_id`=". $shopproductId.",`shop_id`=".$shop_id);
        // }
        $image['product_id'] = 0;
        $image['image'] = $data['picpath'];
        $image['shop_product_id'] = $shopproductId;
        M('shop_product_image')->add($image);
        $master['product_id'] = 0;
        $master['image'] = $data['iamgepath'];
        $master['shop_product_id'] = $shopproductId;
        $ma=M('shop_product_image')->add($master);
        $shop_product_code = $shop_basic_code.'_1';
        $option['shop_product_code'] = $shop_product_code;
        $option['name'] = $data['classifymodel'];
        $option['shop_product_id'] = $shopproductId;
        $options = M('shop_product_option')->add($option);
    }
    //查看货架修改Y位置
    public function  repairy(){
        $requestjson = file_get_contents('php://input');
        $data = json_decode($requestjson, true);
        $shelf_product_id = $data['shelf_product_id'];
        $y = $data['y'];
        $save = $this->db->query("UPDATE shelf_product SET shelf_layer=".$y." WHERE shelf_product_id=".$shelf_product_id);
    }
    //查看货架修改X位置
    public function  repairx(){
        $requestjson = file_get_contents('php://input');
        $data = json_decode($requestjson, true);
        $shelf_product_id = $data['shelf_product_id'];
        $x = $data['x'];
        $save = $this->db->query("UPDATE shelf_product SET layer_position=".$x." WHERE shelf_product_id=".$shelf_product_id);
    }
    //店铺扫码上传商品
    public function examine(){
      $searchInput = trim(I('get.searchInput'));
      $shopid = trim(I('get.shopid'));
      $shelf_id = trim(I('get.shelf_id'));
      $sql = $this->db->query("SELECT * from  shop_product where shop_id=".$shopid." AND  sku=".$searchInput)->row;
      if(!empty($sql)){
         $where['product_id']=$sql['product_id'];
         $product_code = M('product')
          ->where($where)
          ->field('product_code')
          ->select();
          //var_dump($product_code);die;
          if(empty($product_code)){
            $product_code = 0;
          }else{
             $product_code =  $product_code[0]['product_code'];
          }
          $shelf_product =  $this->db->query("INSERT INTO `" . DB_PREFIX . "shelf_product` SET shelf_id = ".$shelf_id." , product_id = '" . (int)$sql['product_id'] . "', product_code = '" . $this->db->escape($product_code) . "', shelf_layer = 0, layer_position = 0, attr_list = 0, group_name =0, show_qty = 1, min_order_qty = 1, date_added = NOW(), `stock_qty`=0, `stock_qty_temp`=0, `shop_inventory_id`=0 ,`shop_product_id`=".$sql['shop_product_id'].",`shop_id`=".$shopid);
           if($shelf_product){
              $data = 'success';
            }
      }else{
          $data = 'error';
      }
      $this->response->setOutput(json_encode($data));

    }

}
